package com.webguard.outlierdetection.controller;


import com.webguard.outlierdetection.dto.RegisterRequest;
import com.webguard.outlierdetection.pojo.Result;
import com.webguard.outlierdetection.pojo.User;
import com.webguard.outlierdetection.service.UserService;
import com.webguard.outlierdetection.untils.JwtUtil;
import com.webguard.outlierdetection.untils.Md5Util;
import com.webguard.outlierdetection.untils.ThreadLocalUtil;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

import java.util.regex.Matcher;

@Slf4j//自动定义log
@RestController
@RequestMapping("/user")
@Validated//参数校验
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result register( @Valid RegisterRequest request) {
        log.info("Received request: " + request);
        log.info("register user");

        User user1 = userService.findByUserName(request.getUsername());
        User user2 = userService.findByEmail(request.getEmail());

        if (user1 == null && user2 == null) {
            log.info("user not found");
            userService.register(request.getUsername(), request.getPassword(), request.getEmail());
            return Result.success();
        } else {
            if (user1 != null && user2 != null) {
                log.info("user and email already exist");
                return Result.error("用户名和邮箱都已被占用");
            } else if (user1 != null) {
                log.info("user already exist");
                return Result.error("用户名已被占用");
            } else {
                return Result.error("邮箱已被占用");
            }
        }
    }

    @PostMapping("/loginByEmail")
    public Result loginByEmail(String email, @Pattern(regexp = "^\\S{5,16}$")String password){
        log.info("login user");
        User user = userService.findByEmail(email);
        if(user == null){
            log.info("user not found");
            return Result.error("邮箱错误");
        }
        if(Md5Util.checkPassword(password,user.getPassword())){
            log.info("login success");
            Map<String, Object> claims = new HashMap<>();
            claims.put("username", user.getUsername());
            claims.put("email", user.getEmail());
            claims.put("password", user.getPassword());
            claims.put("id",user.getId());
            return Result.success(JwtUtil.genToken(claims));
        }
        log.info("login failed");
        return Result.error("密码错误");
    }

    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$")String username, @Pattern(regexp = "^\\S{5,16}$")String password){
        log.info("login user");
        User user = userService.findByUserName(username);
        if(user == null){
            log.info("user not found");
            return Result.error("用户名错误");
        }
        if(Md5Util.checkPassword(password,user.getPassword())){
            log.info("login success");
            Map<String, Object> claims = new HashMap<>();
            claims.put("username", user.getUsername());
            claims.put("email", user.getEmail());
            claims.put("password", user.getPassword());
            claims.put("id",user.getId());
            return Result.success(JwtUtil.genToken(claims));
        }
        log.info("login failed");
        return Result.error("密码错误");
    }

    @GetMapping("/userInfo")
    public Result userinfo() {//@RequestHeader(name = "Authorization") String token
//        Map<String, Object> claims = JwtUtil.parseToken(token);

        Map<String, Object> claims = ThreadLocalUtil.get();
        User user = userService.findById(claims.get("id").toString());
        log.info("userinfo");
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        log.info("update user");
        User user1 = userService.findByUserName(user.getUsername());
        User user2 = userService.findByEmail(user.getEmail());
        User user3 = userService.findById(String.valueOf(user.getId()));
        if(!user3.getUsername().equals(user.getUsername()) && !user3.getEmail().equals(user.getEmail()) ){
            if(user1 == null && user2 == null) {
                userService.update(user);
            } else if(user1 != null && user2 == null) {
                return Result.error("用户名与其他人重复");
            } else if(user1 == null && user2 != null) {
                return Result.error("邮箱与其他人重复");
            } else{
                return Result.error("用户名和邮箱都和其他人重复");
            }

        } else if(!user3.getUsername().equals(user.getUsername())){
            if(user1 == null) {
                userService.update(user);
            } else {
                return Result.error("用户名与其他人重复");
            }
        }else if(!user3.getEmail().equals(user.getEmail())){
            if(user2 == null) {
                userService.update(user);
            } else {
                return Result.error("邮箱与其他人重复");
            }
        } else {
            userService.update(user);
        }

        return Result.success();
    }


    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> map) {
        log.info("update password");
        String oldPassword = map.get("old_pwd");
        String newPassword = map.get("new_pwd");
        String confirmPassword = map.get("re_pwd");
        if(!StringUtils.hasLength(oldPassword)|| !StringUtils.hasLength(newPassword) || !StringUtils.hasLength(confirmPassword)){
            return Result.error("参数不完整");
        }

        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("^\\S{5,16}$");
        Matcher matcher = pattern.matcher(map.get("new_pwd"));
        if(!matcher.matches()){
            return Result.error("新密码不符合格式");
        }

        Map<String, Object> claims = ThreadLocalUtil.get();
        User user = userService.findById(claims.get("id").toString());
        if(!Md5Util.getMD5String(oldPassword).equals(user.getPassword())){
            return Result.error("旧密码不正确");
        }
        if(!newPassword.equals(confirmPassword)){
            return Result.error("两次填写的新密码不一致");
        }
        userService.updatePwd(Md5Util.getMD5String(newPassword),user.getId());
        return Result.success();
    }

    @GetMapping("/resetPwd")
    public Result resetPwd() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        User user = userService.findById(claims.get("id").toString());
        userService.updatePwd(Md5Util.getMD5String("12345"),user.getId());
        return Result.success();
    }
}
